<?php
namespace App\Admin\Controllers\Stocking;

use App\Importer\Basics\BImporter;
use App\Importer\Stocking\Sku\SkuImporter;
use App\Jobs\Stocking\AreaEuEstimateJob;
use App\Jobs\Stocking\AreaEuSkuRatioJob;
use App\Jobs\Stocking\CountryEstimateJob;
use App\Jobs\Stocking\CountrySkuRatioJob;
use App\Models\Basics\SysCountry;
use App\Models\Product\ProductClassify;
use App\Models\Product\ProductSku;
use App\Models\SsBasic\CountryClassifyEstimate;
use App\Models\SsBasic\CountrySkuEstimate;
use App\Models\SsBasic\CountryStockingSkuRatio;
use App\Util\RExcel;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class CountrySkuUploadController extends AdminController{

    protected $title = '上传文件';

    protected function grid()
    {
        $type = request('type');
        return view("stocking.country-sku.upload.index",compact('type'));
    }

    public function upload(Request $request){

        $file = $request->file('source_file');
        if ($file->isValid()) {
            $action = $request->get('action');
            $re = $this->{'_import'.$action}($file);
            if(is_array($re)) {
                if($re['flag']){
                    admin_toastr('文件：'.$re['data'].' 上传成功！');
                }else{
                    admin_toastr($re['data'],'error');
                }
            }else{
                return $re;
            }
        }else{
            admin_toastr('无效文件！','error');
        }
        return back()->withInput();
    }

    private function _importRatio(UploadedFile $file){
        try{
            $data = Excel::toArray(new SkuImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            $errors = [];
            $count = 1;
            $arr = [];
            $item = [];
            $classifyKey = [];
            foreach($data as $row){
                $count++;
                $_country = $row[0] ? trim($row[0]) : '';
                $_sku = $row[1] ? trim($row[1]) : '';
                $_ratio = $row[2] ? trim($row[2]) : '';
                if(!$_country || !$_sku){
                    $errors[$count] = '必填项为空';
                    continue;
                }
                $country = strtoupper($_country);
                $key = $country.'_'.$_sku;
                if(!in_array($key,$arr)){
                    $arr[$count] = $key;
                }else{
                    $errors[$count] = '重复记录';
                    continue;
                }
                $countryId = SysCountry::getIdByCountry($_country);
                if(!$countryId){
                    $errors[$count] = $_country.'系统不存在该国家';
                    continue;
                }
                $pSkuId = ProductSku::getValueByCode($_sku,'id');
                if(!$pSkuId){
                    $errors[$count] = $_sku.'系统不存在该产品';
                    continue;
                }
                $classifyId = ProductSku::getValueById($pSkuId, 'classify_id');
                if(!$classifyId){
                    $errors[$count] = $_sku.'系统不存在该产品的品类';
                    continue;
                }
                //EU国家的预估品类
                if(!in_array($classifyId,$classifyKey)){
                    $classifyKey[] = $classifyId;
                }

                DB::beginTransaction();
                $countrySkuRatio = CountryStockingSkuRatio::query()->firstOrNew(['area_psku' => $countryId.'_'.$pSkuId]);
                $countrySkuRatio->area_id = SysCountry::getAreaIdByCountryId($countryId);
                $countrySkuRatio->country_id = $countryId;
                $countrySkuRatio->psku_id = $pSkuId;
                $countrySkuRatio->classify_id = $classifyId;
                $countrySkuRatio->ratio = (float)$_ratio;
                if($countrySkuRatio->save()){
                    $item[] = $countrySkuRatio;
                    DB::commit();
                }else{
                    DB::rollBack();
                }
            }

            if(!empty($item)){
                //1.（EU国家）更新备货sku销售比例
                CountrySkuRatioJob::dispatch($item);

                sleep(2);

                //2.（EU站点）更新备货sku销售比例
                AreaEuSkuRatioJob::dispatch($item);
            }
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    /**
     * 品类预估
     * @param UploadedFile $file
     * @return array|\Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    private function _importEstimate(UploadedFile $file){
        try{

            $data = Excel::toArray(new BImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            $errors = [];
            $count = 1;
            $arr = [];
            $item = [];
            $classifyKey = [];
            foreach($data as $row){
                $count++;
                $_country = $row[0] ? trim($row[0]) : '';
                $_classify = $row[1] ? trim($row[1]) : '';
                $j = 2;
                for($i = 0; $i < CountrySkuEstimate::ESTIMATE_NUM; $i++){
                    ${'estimate_num'.$i} = is_null($row[$j]) ? null : trim($row[$j]);
                    $j++;
                }
                if(!$_country || !$_classify){
                    $errors[$count] = '必填项为空';
                    continue;
                }

                $country = strtoupper($_country);
                $key = $country.'_'.$_classify;
                if(!in_array($key,$arr)){
                    $arr[$count] = $key;
                }else{
                    $errors[$count] = '重复记录';
                    continue;
                }

                $countryId = SysCountry::getIdByCountry($country);
                if(!$countryId){
                    $errors[$count] = $_country.'系统不存在国家';
                    continue;
                }

                $classifyId = ProductClassify::getIdByTitle($_classify);
                if(!$classifyId){
                    $errors[$count] = $_classify.'系统不存在该品类';
                    continue;
                }
                //EU国家的预估品类
                if(!in_array($classifyId,$classifyKey)){
                    $classifyKey[] = $classifyId;
                }

                DB::beginTransaction();
                //EU国家
                $countryEstimate = CountryClassifyEstimate::query()
                    ->firstOrNew([
                        'country_id' => $countryId,
                        'classify_id' => $classifyId
                    ]);
                for($i = 0; $i < CountrySkuEstimate::ESTIMATE_NUM; $i++){
                    if(!is_null(${'estimate_num'.$i})){
                        $countryEstimate->{'estimate_num'.$i} = ${'estimate_num'.$i};
                    }
                }
                $countryEstimate->area_id = SysCountry::getAreaIdByCountryId($countryId);
                if($countryEstimate->save()){
                    $item[] = $countryEstimate;
                    DB::commit();
                }else{
                    DB::rollBack();
                }
            }

            if(!empty($item)){
                //1.（EU国家）更新备货预估
                CountryEstimateJob::dispatch($item);

                sleep(2);

                //2.（EU站点）更新备货预估
                AreaEuEstimateJob::dispatch($item);
            }
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            DB::rollBack();
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    public function template(Request $request){
        $temp = $request->get('temp');
        $suffix = $request->get('suffix','xlsx');
        return Storage::disk('admin')->download("template/{$temp}-template.{$suffix}");
    }
}
